'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

    constructor(ctx) {
        super(ctx);
        this.createRule = {
          userid:   'string',
          username: 'string',
          password: 'string',
          phone:    'string',
          roll:     'string',
          group:    'string',
        };
        this.loginRule = {
            username: 'string',
            password: 'string',
        }
    }

    async register() {
        const { ctx } = this;
        ctx.validate(this.createRule, ctx.query);
        const user = await ctx.service.users.register(ctx.query);
        if (user) {
            ctx.status = 201;
            ctx.body = user;
        } else {
            ctx.status = 409;
        }
        
    }

    async login() {
        const { ctx } = this;
        console.log('login');
        ctx.validate({ 
            username: {type: 'string'},
            password: {type: 'string'} 
        }, ctx.query);
        const user = await ctx.service.users.login(ctx.query.username, ctx.query.password);
        if (user) {
            ctx.status = 200;
            ctx.body = user;
        } else {
            ctx.status = 401;
        }
    }

    async show() {
        const { ctx } = this;
        const user = await ctx.service.users.getUser(ctx.params.id);  
        if (user) {
            ctx.status = 200;
            ctx.body = user;
        } else {
            ctx.status = 401;
        }
    }

    async edit() {
        const { ctx } = this;
        const res = await ctx.service.users.updateUser(ctx.params.id, ctx.query);  
        if (res) {
            ctx.status = 200;
        } else {
            ctx.status = 401;
        }
    }
    
}

module.exports = UserController;